package com.qingfeng.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonPFilter implements Filter {

	private final static String JSON = ".json";
	private final static String JPEG = ".jpeg";
	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response =(HttpServletResponse) resp;
		String uri = request.getServletPath();
		
        if (uri.indexOf(JSON) > 0||uri.indexOf(JPEG)>0) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Version,User-agent,Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
        }
        filterChain.doFilter(req, resp);
        /*if (uri.indexOf(JSON) > 0||uri.indexOf(JPEG)>0) {
            resp.getWriter().flush();
            resp.getWriter().close();
        }
        resp.getWriter().flush();
        resp.getWriter().close();*/
		/*String callback = request.getParameter("callback");
		String uri = request.getServletPath();
		if (uri.indexOf(JSON) > 0) {
			resp.setContentType("application/json");
			resp.setCharacterEncoding("UTF-8");
			if (!StringUtils.isEmpty(callback)) {
				resp.getWriter().print(callback + "(");
			}
		}
		filterChain.doFilter(req, resp);
		if (uri.indexOf(JSON) > 0) {
			if (!StringUtils.isEmpty(callback)) {
				resp.getWriter().print(")");
			}
			resp.getWriter().flush();
			resp.getWriter().close();
		}*/

	}

	public void init(FilterConfig cfg) throws ServletException {

	}

}
